﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Web;
using System.Text.RegularExpressions;
using System.Threading;

namespace FreeBroker
{
    public class Helper
    {

        public static string base64Encode(string data)
        {
            try
            {
                byte[] encData_byte = new byte[data.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(data);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode: " + e.Message);
            }
        }

        public static string base64Decode(string data)
        {
            try
            {
                UTF8Encoding encoder = new UTF8Encoding();
                Decoder utf8Decode = encoder.GetDecoder();

                byte[] todecode_byte = Convert.FromBase64String(data);
                int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
                char[] decoded_char = new char[charCount];
                utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
                string result = new String(decoded_char);
                return result;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Decode: " + e.Message);
            }
        }


        public static string extractUrlAttribute(string url, string attrib)
        {
            string attribValue = null;
            if (url != null && attrib != null)
            {
                string[] urlParts = url.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
                if (urlParts != null && urlParts.Length > 0)
                {
                    for (int j = 0; j < urlParts.Length; j++)
                    {
                        int found = urlParts[j].IndexOf(attrib + "=");
                        if (found != -1)
                        {
                            attribValue = urlParts[j].Substring(found + attrib.Length + 1).Trim();
                            break;
                        }
                    }
                }
            }

            return attribValue;
        }

        /// <summary>
        ///     Converts a timestamp value in long format to a DateTime object.
        /// </summary>
        /// <param name="ts"></param>
        /// <returns>the converted object.</returns>
        public static DateTime timestamp2DateTime(long ts)
        {
            DateTime date = new DateTime(1970, 1, 1);
            date = date.AddMilliseconds((double)ts);
            date = date.ToLocalTime();
            return date;
        }

        /// <summary>
        ///     Converts a DateTime object to a timestamp in long format.
        /// </summary>
        /// <param name="time"></param>
        /// <returns>the timestamp.</returns>
        public static long dateTime2Timestamp(DateTime time)
        {
            TimeSpan span = time - new DateTime(1970, 1, 1);
            long ts = (long)span.TotalMilliseconds;
            return ts;
        }

        public static string UnescapeHtmlString(string escaped)
        {
            return HttpUtility.HtmlDecode(escaped);
        }

        public static string EscapeHtmlString(string unescaped)
        {
            return SecurityElement.Escape(unescaped);
        }

        public string EscapeXmlString(string URL)
        {
            //Avoid errors if the string is already escaped for xml use
            for (int i = 0; i < URL.Length - 1; i++)
            {
                if (URL[i] == '&')
                {
                    switch (URL[i + 1])
                    {
                        case 'a':
                            if ((i + 5 < URL.Length) && (URL.Substring(i, 6) == "'"))
                            {
                                continue;
                            }
                            else
                            {
                                if ((i + 4 < URL.Length) && (URL.Substring(i, 5) == "&"))
                                {
                                    continue;
                                }
                                else
                                {
                                    //Escape it
                                    URL = URL.Insert(i + 1, "amp;");
                                }
                            }
                            break;
                        case 'q':
                            if ((i + 5 < URL.Length) && (URL.Substring(i, 6) == "\""))
                            {
                                continue;
                            }
                            else
                            {
                                //Escape it
                                URL = URL.Insert(i + 1, "amp;");
                            }
                            break;
                        case 'g':
                            if ((i + 3 < URL.Length) && (URL.Substring(i, 4) == ">"))
                            {
                                continue;
                            }
                            else
                            {
                                //Escape it
                                URL = URL.Insert(i + 1, "amp;");
                            }
                            break;
                        case 'l':
                            if ((i + 3 < URL.Length) && (URL.Substring(i, 4) == "<"))
                            {
                                continue;
                            }
                            else
                            {
                                //Escape it
                                URL = URL.Insert(i + 1, "amp;");
                            }
                            break;
                        default://Escape it
                            URL = URL.Insert(i + 1, "amp;");
                            break;
                    }
                }
            }

            URL = URL.Replace("'", "'");
            URL = URL.Replace("\"", "\"");
            URL = URL.Replace(">", ">");
            URL = URL.Replace("<", "<");

            return URL;
        }

        //public static Match FindMatch(Regex regex, string text)
        //{

        //}

        //private Match MatchText(Regex regex, string text)
        //{
        //    Thread th1 = new Thread(new ParameterizedThreadStart(RunRegex));
        //    th1.IsBackground = true;
        //    th1.Start();

        //}

        //private void RunRegex()
        //{

        //}
    }
}
